﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VersionComparer.Base;

namespace VersionComparer.Views
{
    public partial class ConnectionStringTest : Form
    {
        Stopwatch stopwatch = new Stopwatch();
        int totalTime = 0;
        Timer timer = new Timer();

        public ConnectionStringTest()
        {
            InitializeComponent();
            StartPosition = FormStartPosition.CenterScreen;
        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            Close();
            
        }

        private void ConnectionStringTest_Load(object sender, EventArgs e)
        {

        }

        private void Stop()
        {
            timer.Stop();
            progressBar1.Value = progressBar1.Maximum;
        }
        private void TryConnection(ManagedThread threadManaged)
        {
            
            try
            {
                using (SqlConnection sqlConnection = new SqlConnection(ConnectionString))
                {
                    sqlConnection.Open();
                }
                if (Visible)
                {
                    this.Execute(Stop);
                    MessageBox.Show("Test successfull", "Connection successfull", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception e)
            {
                if (Visible)
                {
                    this.Execute(Stop);
                    MessageBox.Show(e.Message, "Error connecting", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                
            }
            this.Execute(Close);

        }
       
        protected override void OnLoad(EventArgs e)
        {
            SqlConnection sqlConnection = new SqlConnection(ConnectionString);
            totalTime = sqlConnection.ConnectionTimeout;
            progressBar1.Maximum = totalTime * 1000 + 5000;
            stopwatch.Start();
            timer.Interval = 100;
            timer.Tick += timer_Tick;
            timer.Start();
            label1.Text = ConnectionString;
            ThreadManager threadManager = new ThreadManager();
            threadManager.StartNew(TryConnection);

            base.OnLoad(e);
        }
        public string ConnectionString
        {
            get;
            set;
        }
        void timer_Tick(object sender, EventArgs e)
        {
            int newvalue = (int)stopwatch.ElapsedMilliseconds;
            if (newvalue > progressBar1.Maximum)
            {
                newvalue = progressBar1.Maximum;
                timer.Stop();
            }
            progressBar1.Value = newvalue;
        }
        
    }
}
